from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.urls import reverse

def home(request):
    """系统首页"""
    # 如果用户已登录，根据角色重定向到对应仪表板
    if request.user.is_authenticated:
        return redirect(get_dashboard_redirect(request.user))
    return render(request, 'home.html')

@login_required
def dashboard(request):
    """用户仪表板 - 根据角色重定向"""
    return redirect(get_dashboard_redirect(request.user))

@login_required
def dashboard_customer(request):
    """客户仪表板"""
    from tickets.models import Ticket
    from assets.models import Asset
    from notifications.views import get_user_notifications
    
    # 获取客户的工单统计
    tickets = Ticket.objects.filter(created_by=request.user)
    ticket_stats = {
        'total': tickets.count(),
        'pending': tickets.filter(status='pending').count(),
        'in_progress': tickets.filter(status='in_progress').count(),
        'completed': tickets.filter(status='completed').count(),
    }
    
    # 获取客户的设备统计
    assets = Asset.objects.filter(assigned_to=request.user)
    asset_stats = {
        'total': assets.count(),
        'active': assets.filter(status='active').count(),
        'maintenance': assets.filter(status='maintenance').count(),
    }
    
    # 获取最新工单
    recent_tickets = tickets.order_by('-created_at')[:5]
    
    # 获取用户通知
    notifications = get_user_notifications(request.user)
    
    context = {
        'user': request.user,
        'ticket_stats': ticket_stats,
        'asset_stats': asset_stats,
        'recent_tickets': recent_tickets,
        'notifications': notifications,
    }
    return render(request, 'dashboard_customer.html', context)

@login_required  
def dashboard_technician(request):
    """技术人员仪表板"""
    from tickets.models import Ticket
    from notifications.views import get_user_notifications
    
    # 获取技术人员的工单统计 - 包括所有状态
    tickets = Ticket.objects.filter(assigned_to=request.user)
    ticket_stats = {
        'total': tickets.count(),
        'applied': tickets.filter(status='applied').count(),
        'registered': tickets.filter(status='registered').count(),
        'assigned': tickets.filter(status='assigned').count(),
        'testing': tickets.filter(status='testing').count(),
        'repairing': tickets.filter(status='repairing').count(),
        'quality_check': tickets.filter(status='quality_check').count(),
        'completed': tickets.filter(status='completed').count(),
        'returned': tickets.filter(status='returned').count(),
    }
    
    # 获取已分配、检测中和维修中的工单（技术人员需要能看到所有能处理的工单）
    assigned_tickets = tickets.filter(status='assigned')
    testing_tickets = tickets.filter(status='testing')
    repairing_tickets = tickets.filter(status='repairing')
    
    # 获取用户通知
    notifications = get_user_notifications(request.user)
    
    context = {
        'user': request.user,
        'ticket_stats': ticket_stats,
        'assigned_tickets': assigned_tickets,
        'testing_tickets': testing_tickets,
        'repairing_tickets': repairing_tickets,
        'notifications': notifications,
    }
    return render(request, 'dashboard_technician.html', context)

@login_required
def dashboard_admin(request):
    """管理员仪表板"""
    from django.contrib.auth.models import User
    from tickets.models import Ticket
    from assets.models import Asset
    from django.utils import timezone
    from notifications.views import get_user_notifications
    
    # 获取系统统计信息
    stats = {
        'users_total': User.objects.count(),
        'tickets_total': Ticket.objects.count(),
        'assets_total': Asset.objects.count(),
        'tickets_today': Ticket.objects.filter(created_at__date=timezone.now().date()).count(),
    }
    
    # 获取所有状态的待处理工单（管理员可以处理所有状态）
    applied_tickets = Ticket.objects.filter(status='applied')
    registered_tickets = Ticket.objects.filter(status='registered')
    assigned_tickets = Ticket.objects.filter(status='assigned')
    testing_tickets = Ticket.objects.filter(status='testing')
    repairing_tickets = Ticket.objects.filter(status='repairing')
    quality_check_tickets = Ticket.objects.filter(status='quality_check')
    completed_tickets = Ticket.objects.filter(status='completed')
    
    # 获取用户通知
    notifications = get_user_notifications(request.user)
    
    context = {
        'user': request.user,
        'stats': stats,
        'applied_tickets': applied_tickets,
        'registered_tickets': registered_tickets,
        'assigned_tickets': assigned_tickets,
        'testing_tickets': testing_tickets,
        'repairing_tickets': repairing_tickets,
        'quality_check_tickets': quality_check_tickets,
        'completed_tickets': completed_tickets,
        'applied_count': applied_tickets.count(),
        'registered_count': registered_tickets.count(),
        'assigned_count': assigned_tickets.count(),
        'testing_count': testing_tickets.count(),
        'repairing_count': repairing_tickets.count(),
        'quality_check_count': quality_check_tickets.count(),
        'completed_count': completed_tickets.count(),
        'notifications': notifications,
    }
    return render(request, 'dashboard_admin.html', context)

@login_required
def dashboard_receptionist(request):
    """前台仪表板"""
    from tickets.models import Ticket
    from django.db.models import Q
    from notifications.views import get_user_notifications
    
    # 获取待登记签收的工单
    pending_registration = Ticket.objects.filter(status='applied')
    
    # 获取待返还的工单
    pending_return = Ticket.objects.filter(status='completed')
    
    # 获取已处理工单：已登记签收和已返还的工单
    processed_tickets = Ticket.objects.filter(
        Q(status='registered') | Q(status='returned')
    ).order_by('-updated_at')[:10]
    
    # 获取用户通知
    notifications = get_user_notifications(request.user)
    
    context = {
        'user': request.user,
        'pending_registration': pending_registration,
        'pending_return': pending_return,
        'processed_tickets': processed_tickets,
        'registration_count': pending_registration.count(),
        'return_count': pending_return.count(),
        'processed_count': processed_tickets.count(),
        'notifications': notifications,
    }
    return render(request, 'dashboard_receptionist.html', context)

@login_required
def dashboard_quality_checker(request):
    """质检员仪表板"""
    from tickets.models import Ticket
    from notifications.views import get_user_notifications
    
    # 获取待质检的工单
    pending_quality_check = Ticket.objects.filter(status='repairing')
    
    # 获取质检历史
    quality_check_history = Ticket.objects.filter(status__in=['quality_check', 'completed', 'returned'])
    
    # 获取用户通知
    notifications = get_user_notifications(request.user)
    
    context = {
        'user': request.user,
        'pending_quality_check': pending_quality_check,
        'quality_check_history': quality_check_history.order_by('-updated_at')[:10],
        'pending_count': pending_quality_check.count(),
        'history_count': quality_check_history.count(),
        'notifications': notifications,
    }
    return render(request, 'dashboard_quality_checker.html', context)

def get_dashboard_redirect(user):
    """根据用户角色返回对应的仪表板URL"""
    if hasattr(user, 'profile'):
        if user.profile.role == 'customer':
            return reverse('dashboard_customer')
        elif user.profile.role == 'technician':
            return reverse('dashboard_technician')
        elif user.profile.role == 'receptionist':
            return reverse('dashboard_receptionist')
        elif user.profile.role == 'quality_checker':
            return reverse('dashboard_quality_checker')
        elif user.profile.role == 'admin' or user.is_staff:
            return reverse('dashboard_admin')
    
    # 默认重定向到客户仪表板
    return reverse('dashboard_customer')
